package com.riche.contractbackend.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.riche.contractbackend.common.ErrorCode;
import com.riche.contractbackend.exception.BusinessException;
import com.riche.contractbackend.mapper.UserMapper;
import com.riche.contractbackend.model.domain.User;
import com.riche.contractbackend.service.UserService;
import com.riche.contractbackend.utils.AlgorithmUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.DigestUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

import static com.riche.contractbackend.contant.UserConstant.ADMIN_ROLE;
import static com.riche.contractbackend.contant.UserConstant.USER_LOGIN_STATE;


/**
 * @author Gao Ruiqi
 * @date 2025/8/6 20:25
 * @desc
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Resource
    private UserMapper userMapper;

    private static final String SALT = "riche";


    /**
     * 用户注册
     *
     * @param userAccount   用户账户
     * @param userPassword  用户密码
     * @param checkPassword 校验密码
     * @return
     */
    @Override
    public long userRegister(String userAccount, String userPassword, String checkPassword) {
        // 1. 校验
        if (StringUtils.isAnyBlank(userAccount, userPassword, checkPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数为空");
        }
        if (userAccount.length() < 4) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户账户过短");
        }
        if (userPassword.length() < 8 || checkPassword.length() < 8) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户密码过短");
        }
        // 账户不能包含 特殊字符
        String validPattern = "\\pP|\\pS|\\s+";
        Matcher matcher = Pattern.compile(validPattern).matcher(userAccount);
        if (matcher.find()) {
            return -1;
        }
        if (!userPassword.equals(checkPassword)) {
            return -1;
        }
        // 账户不能重复
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userAccount", userAccount);
        long count = userMapper.selectCount(queryWrapper);
        if (count > 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "该账户已存在！");
        }
        // 2. 加密
        String encryptPassword = DigestUtils.md5DigestAsHex((SALT + userPassword).getBytes());
        // 3. 插入数据
        User user = new User();
        user.setUserAccount(userAccount);
        user.setUserPassword(encryptPassword);
        boolean saveResult = this.save(user);
        if (!saveResult) {
            return -1;
        }
        return user.getId();
    }

    @Override
    public User userLogin(String userAccount, String userPassword, HttpServletRequest request) {
        // 1. 校验
        if (StringUtils.isAnyBlank(userAccount, userPassword)) {
            return null;
        }
        if (userAccount.length() < 4) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户账户过短");
        }
        if (userPassword.length() < 8) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户密码过短");
        }
        // 账户不能包含 特殊字符
        String validPattern = "\\pP|\\pS|\\s+";
        Matcher matcher = Pattern.compile(validPattern).matcher(userAccount);
        if (matcher.find()) {
            return null;
        }
        // 2. 加密
        final String SALT = "riche";
        String encryptPassword = DigestUtils.md5DigestAsHex((SALT + userPassword).getBytes());
        // 查询用户是否存在
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userAccount", userAccount);
        queryWrapper.eq("userPassword", encryptPassword);
        User user = userMapper.selectOne(queryWrapper);
        if (user == null) {
            log.info("user login failed，userAccount cannot match userPassword");
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户不存在!");
        }
        // 用户脱敏
        User safetyUser = getSafetyUser(user);
        // 记录用户的登录态
        request.getSession().setAttribute(USER_LOGIN_STATE, safetyUser);
        log.info("user login success： =======================================>  userId:{}", user.getId());

        return safetyUser;
    }

    /**
     * 用户脱敏
     *
     * @param oldUser
     * @return
     */
    public User getSafetyUser(User oldUser) {
        User safeyUser = new User();
        safeyUser.setId(oldUser.getId());
        safeyUser.setUsername(oldUser.getUsername());
        safeyUser.setUserAccount(oldUser.getUserAccount());
        safeyUser.setAvatarUrl(oldUser.getAvatarUrl());
        safeyUser.setGender(oldUser.getGender());
        safeyUser.setPhone(oldUser.getPhone());
        safeyUser.setEmail(oldUser.getEmail());
        safeyUser.setUserStatus(oldUser.getUserStatus());
        safeyUser.setUserRole(oldUser.getUserRole());
        safeyUser.setCreateTime(oldUser.getCreateTime());
        safeyUser.setUpdateTime(oldUser.getUpdateTime());
        safeyUser.setIsDelete(oldUser.getIsDelete());
        safeyUser.setUserPassword(null);
        safeyUser.setTags(oldUser.getTags());
        safeyUser.setProfile(oldUser.getProfile());
        return safeyUser;
    }

    /**
     * 用户注销
     *
     * @param request
     * @return
     */
    @Override
    public int userLogout(HttpServletRequest request) {
        request.getSession().removeAttribute(USER_LOGIN_STATE);
        return 1;
    }


    /**
     * 内存查询根据标签搜索用户
     *
     * @param tagNameList
     * @return
     */
    @Override
    public List<User> searchUsersByTags(List<String> tagNameList) {
        if (CollectionUtils.isEmpty(tagNameList)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // todo 内存查询
        // 1. 先查询所有用户
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        List<User> userList = userMapper.selectList(wrapper);
        Gson gson = new Gson();
        // 2. 在内存中判断是否包含要求的标签
        return userList.stream().filter(user -> {
            String tagsStr = user.getTags();

            Set<String> userTags = gson.fromJson(tagsStr, new TypeToken<Set<String>>() {
            }.getType());
            // 集合为空时，返回false，作用是链式调用，否则是空的话，就返回新的集合
            userTags = Optional.ofNullable(userTags).orElse(new HashSet<>());
            for (String tagName : tagNameList) {
                if (!userTags.contains(tagName)) {
                    return false;
                }
            }
            return true;
        }).map(this::getSafetyUser).collect(Collectors.toList());
    }

    /**
     * 更新用户
     *
     * @param user      修改的用户
     * @param loginUser 当前登录的用户
     * @return
     */
    @Override
    public Integer updateUser(User user, User loginUser) {
        log.info("user update： =======================================>  user:{}, loginUser: {}", user, loginUser);
        Long id = loginUser.getId();

        // 如果不是管理员，只允许修改自己的信息
        if (!isAdmin(loginUser) && !Objects.equals(user.getId(), loginUser.getId())) {
            throw new BusinessException(ErrorCode.NO_AUTH, "无权限");
        }
        User oldUser = userMapper.selectById(id);
        if (oldUser == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户不存在");
        }
        int i = userMapper.updateById(user);
        log.info("user update success： =======================================>  userId:{}", user.getId());
        if (i == 0) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "更新失败");
        }
        return i;
    }

    @Override
    public User getLoginUser(HttpServletRequest request) {
        if (request == null) {
            return null;
        }
        User currentUser = (User) request.getSession().getAttribute(USER_LOGIN_STATE);
        if (currentUser == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN, "未登录");
        }

        return currentUser;
    }


    /**
     * sql查询根据标签搜索用户
     *
     * @param tagNameList
     * @return
     */
    @Deprecated  // 表示已过时
    public List<User> searchUsersByTagsBySql(List<String> tagNameList) {
        if (CollectionUtils.isEmpty(tagNameList)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // todo SQL查询
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        for (String tagName : tagNameList) {
            queryWrapper = queryWrapper.like("tags", tagName);
        }
        List<User> userList = userMapper.selectList(queryWrapper);
        return userList.stream().map(this::getSafetyUser).collect(Collectors.toList());
    }


    /**
     * 校验管理员和空
     *
     * @param request
     * @return
     */
    public boolean isAdmin(HttpServletRequest request) {
        // 鉴权 - 只管理员可查询
        User user = (User) request.getSession().getAttribute(USER_LOGIN_STATE);
        return user != null && user.getUserRole() == ADMIN_ROLE;
    }

    /**
     * 校验管理员和空
     *
     * @param user
     * @return
     */
    public boolean isAdmin(User user) {
        return user != null && user.getUserRole() == ADMIN_ROLE;
    }

    @Override
    public List<User> matchUsers(long num, User loginUser) {
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.isNotNull("tags");
        List<User> userList = this.list(userQueryWrapper);
        String tags = loginUser.getTags();
        Gson gson = new Gson();
        // 登录用户的tags字符串
        List<String> tagList = gson.fromJson(tags, new TypeToken<List<String>>(){}.getType());
        SortedMap<Integer, Long> indexDistanceMap = new TreeMap<>();
        for (int i = 0; i < userList.size(); i++) {
            User user = userList.get(i);
            String userTags = user.getTags();
            // 无标签
            if (StringUtils.isBlank(userTags) || Objects.equals(user.getId(), loginUser.getId())) {
                continue;
            }
            List<String> userTagList = gson.fromJson(userTags, new TypeToken<List<String>>(){}.getType());
            // 计算分数
            long minDistance = AlgorithmUtils.minDistance(tagList, userTagList);
            indexDistanceMap.put(i, minDistance);
        }
        // 获取相似度最高的
        List<Integer> maxDistanceIndexList = indexDistanceMap.keySet().stream().limit(num).collect(Collectors.toList());
        return maxDistanceIndexList.stream()
                .map(index -> getSafetyUser(userList.get(index)))
                .collect(Collectors.toList());
    }
}
